import 'package:fate_blind_box/models/blind_detail.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/bottom_sheet.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/material.dart';
import 'package:fate_blind_box/widget/date_picker/flutter_datetime_picker.dart';

class BlindDetailUi extends StatelessWidget {

  final String? datingId;
  final int type;

  const BlindDetailUi({Key? key, required this.datingId, this.type = 0}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _BlindDetailWidget(datingId, type);
  }
}

class _BlindDetailWidget extends StatefulWidget {
  final String? datingId;
  final int type;
  const _BlindDetailWidget(this.datingId, this.type, {Key? key}) : super(key: key);

  @override
  State<_BlindDetailWidget> createState() => _BlindDetailWidgetState();
}

class _BlindDetailWidgetState extends State<_BlindDetailWidget> {

  final _formData = <String, BlindDetailItem>{};
  final _formKey = GlobalKey<FormState>();
  late bool _isPublish;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _isPublish = widget.datingId?.isEmpty == true;
    _formData['type'] = BlindDetailItem(key: "模式", value: "", hint: "请选择", paramsKey: "type");
    _formData['inviteMethod'] = BlindDetailItem(key: "类型", value: "", hint: "请选择", paramsKey: "inviteMethod");
    _formData['creditAmount'] = BlindDetailItem(key: "费用", value: "", hint: "请输入", paramsKey: "creditAmount");
    _formData['startTime'] = BlindDetailItem(key: "时间", value: "", hint: "请选择", paramsKey: "startTime");
    _formData['location'] = BlindDetailItem(key: "地点", value: "", hint: "请输入", paramsKey: "location");
    _formData['content'] = BlindDetailItem(key: "约会心语", value: "", hint: "请输入", paramsKey: "content");
    _formData.forEach((key, value) { value.controller = TextEditingController(); });
    if (!_isPublish) {
      _getInfo();
    }
  }

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      title:"约会详情",
      elevation: 2,
      childWidget: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            children: _buildForm(),
          ),
        ),
      ),
    );
  }

  List<Widget> _buildForm() {
    final list = <BlindDetailItem>[];
    _formData.forEach((key, value) {
      if (key != 'content') {
        list.add(value);
      }
    });
    final widgets = list.map((e) {
      return _formItem(e, _isPublish);
    }).toList();
    widgets.add(_buildDes(_isPublish));
    widgets.add(_buildSubmit(_isPublish ? "发布" : "接受邀请"));
    return widgets;
  }

  Widget _formItem(BlindDetailItem e, bool publish) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      height: 52,
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(width: 1, color: ThemeColor.dividerColor))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            e.key,
            style: TextStyle(color: ThemeColor.textColor, fontSize: 14),
          ),
          Expanded(child: _formEdit(e)),
          const SizedBox(width: 8,),
          publish ? Icon(
                  Icons.arrow_forward_ios,
                  size: 16,
                  color: ThemeColor.textColorSecond,
                ) : const SizedBox(width: 0, height: 0,)
        ],
      ),
    );
  }

  Widget _formText(String s) {
    return Text(
      s,
      textAlign: TextAlign.right,
      style: TextStyle(
        color: ThemeColor.textColorSecond,
      ),
    );
  }

  Widget _formEdit(BlindDetailItem e) {
    final enable = (e.paramsKey != 'type' &&
        e.paramsKey != 'inviteMethod' && e.paramsKey != 'startTime') && _isPublish;
    return enable ? _formEditItem(e, enable) : GestureDetector(
      onTap: () async {
        if (_isPublish) {
          switch(e.paramsKey) {
            case 'type':
              final items = ['吃饭'];
              final res = await BottomSheetDialog.showMenuByNames(context, items);
              if (res != null && res >= 0) {
                _formData[e.paramsKey]?.paramsValue = res;
                _formData[e.paramsKey]?.value = items[res];
                e.controller?.text = items[res];
              }
              break;
            case 'inviteMethod':
              final items = ["邀请人付费"];
              final res = await BottomSheetDialog.showMenuByNames(context, items);
              if (res != null && res >= 0) {
                _formData[e.paramsKey]?.paramsValue = res;
                _formData[e.paramsKey]?.value = items[res];
                e.controller?.text = items[res];
              }
              break;
            case 'startTime':
              DatePicker.showDateTimePicker(
                  context,
                  showTitleActions: true,
                  onConfirm: (date) {
                    final time = date.toString().substring(0, 19);
                    _formData[e.paramsKey]?.paramsValue = time;
                    _formData[e.paramsKey]?.value = time;
                    e.controller?.text = time;
                  },
                  currentTime: DateTime.now(),
                  locale: LocaleType.zh
              );
              break;
            default: break;
          }
        }
      },
      child: _formEditItem(e, enable),
    );
  }

  Widget _formEditItem(BlindDetailItem e, bool enabled) {
    return TextFormField(
      controller: e.controller,
      enabled: enabled,
      // initialValue: _formData[e.paramsKey]?.value,
      decoration: InputDecoration(
        enabled: enabled,
        hintText: e.hint,
        hintStyle: TextStyle(color: ThemeColor.textColorSecond, fontSize: 14),
        border: InputBorder.none
      ),
      textAlign: TextAlign.right,
      onSaved: (value) {
        if (value != null && value.isNotEmpty && enabled) {
          _formData[e.paramsKey]?.value = value;
          _formData[e.paramsKey]?.paramsValue = value;
        }
      },
    );
  }

  Widget _buildDes(bool isEdit) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 10,
          color: const Color(0xFFF7F7F7),
        ),
        const SizedBox(
          height: 16,
        ),
        Container(
          margin: const EdgeInsets.only(left: 12),
          child: Text(
            "约会心语",
            style: TextStyle(
              color: ThemeColor.textColor,
              fontSize: 16,
            ),
          ),
        ),
        const SizedBox(
          height: 10,
        ),
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 12),
          child: _buildDesInput("请输入"),
        )
      ],
    );
  }
  
  Widget _buildDesInput(String hint) {
    return Flexible(child: TextFormField(
      controller: _formData['content']?.controller,
      maxLines: 5,
      enabled: _isPublish,
      decoration: InputDecoration(
        hintText: hint,
        enabled: _isPublish,
        hintStyle: TextStyle(
            color: ThemeColor.textColorSecond, fontSize: 14),
        border: InputBorder.none
      ),
      onSaved: (value) {
        if (value != null && value.isNotEmpty) {
          _formData['content']?.value = value;
          _formData['content']?.paramsValue = value;
        }
      },
    ));
  }
  
  Widget _buildSubmit(String s) {
    return GestureDetector(
      onTap: _isPublish ? _submit : _goDating,
      child: Container(
        margin: const EdgeInsets.fromLTRB(12, 48, 12, 96),
        height: 40,
        decoration: ShapeDecoration(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20),
            ),
            color: ThemeColor.mainColor
        ),
        alignment: Alignment.center,
        child: Text(
          s,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }
  
  _submit() async {
    _formKey.currentState?.save();
    bool flag = false;
    final params = <String, dynamic>{};
    _formData.forEach((key, value) {
      flag = value.paramsValue == null;
      params[key] = value.paramsValue;
    });
    if (flag) {
      ThemeSnackBar.show(context, "请完善信息");
      return;
    }
    final startTime = params['startTime'].toString();
    const day = 1000 * 60 * 60 * 24;
    params["endTime"] = DateTime.fromMillisecondsSinceEpoch(DateTime.parse(startTime).millisecondsSinceEpoch + day).toString().substring(0, 19);
    final res = await Api.getInstance().publishFaithDating(params);
    if (res['code'] == 0) {

    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  _getInfo() async{
    final res = await Api.getInstance().getFaithDatingInfo(widget.type, widget.datingId!);
    if (res['code'] == 0) {
      final data = res['data'];
        setState(() {
          _formData['type']?.controller?.text = data['typeName'];
          _formData['inviteMethod']?.controller?.text = data['inviteMethodName'];
          _formData['creditAmount']?.controller?.text = data['creditAmount'].toString();
          _formData['startTime']?.controller?.text = data['startTimeFormat'];
          _formData['location']?.controller?.text = data['location'];
          _formData['content']?.controller?.text = data['content'];
        });
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  _goDating() async{
    final res = await Api.getInstance().goFaithDating(widget.datingId!);
    if (res['code'] == 0) {

    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }
}
